package com.hnx.admin.aurora.captcha.core;

import com.google.code.kaptcha.text.impl.DefaultTextCreator;

import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.BiFunction;
import java.util.function.Predicate;

/*
创建人： 倔强的头发
创建时间：2025/6/14
功能描述:

*/
public class KaptchaTextCreator  extends DefaultTextCreator {
    private static final int MAX_OPERAND = 10;
    // 定义数学运算及其对应的符号
    private static final Map<String, BiFunction<Integer, Integer, Integer>> OPERATIONS = Map.of(
            "*", (a, b) -> a * b,
            "/", (a, b) -> a / b,
            "+", (a, b) -> a + b,
            "-", (a, b) -> a - b
    );
    // 运算的约束条件
    private static final Map<String, Predicate<int[]>> CONSTRAINTS = Map.of(
            "/", operands -> operands[1] != 0 && operands[0] % operands[1] == 0,
            "-", operands -> operands[0] >= operands[1]
    );

    @Override
    public String getText()
    {
        // 使用 ThreadLocalRandom 获取当前线程的随机数生成器
        ThreadLocalRandom random = ThreadLocalRandom.current();
        // 生成两个随机操作数
        int[] operands = {random.nextInt(MAX_OPERAND), random.nextInt(MAX_OPERAND)};

        // 随机选择运算符
        String[] operators = OPERATIONS.keySet().toArray(new String[0]);
        String operator = operators[random.nextInt(operators.length)];

        // 检查约束条件，如果不满足则重新选择运算符
        if (CONSTRAINTS.getOrDefault(operator, ops -> true).test(operands)) {
            int result = OPERATIONS.get(operator).apply(operands[0], operands[1]);
            return String.format("%d%s%d=?@%d", operands[0], operator, operands[1], result);
        }
        // 如果约束不满足，递归重试
        return getText();
    }
}
